package com.czmh.etc.onlinepubsys.controller.mingchuang;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.mingchuang.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.*;
import com.czmh.etc.onlinepubsys.feign.newrun.constans.UserProperty;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.maper.mingchuang.ApplyInfoMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.CurrentContextMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.MingChuangEtcObuMapper;
import com.czmh.etc.onlinepubsys.maper.mingchuang.MingchuangOrderMapper;
import com.czmh.etc.onlinepubsys.model.EtcFallActivate;
import com.czmh.etc.onlinepubsys.model.SysConfig;
import com.czmh.etc.onlinepubsys.request.mingchuang.*;
import com.czmh.etc.onlinepubsys.services.EtcFallActivateService;
import com.czmh.etc.onlinepubsys.services.SysConfigService;
import com.czmh.etc.onlinepubsys.services.mingchuang.*;
import com.czmh.etc.onlinepubsys.utils.HttpUtils;
import com.czmh.etc.onlinepubsys.utils.PayUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.HttpUtil;
import com.czmh.etc.onlinepubsys.utils.mingchuang.OBUDataEncUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/{version}/api/mingchang/obu")
@Api(tags = "OBU接口【新】- 铭创")
public class ObuController {
    @Autowired
    private UserProperty userProperty;

    @Autowired
    private IObuService obuService;
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private ICurrentContextService currentContextService;
    @Autowired
    private EtcFallActivateService etcFallActivateService;

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ApplyInfoMapper applyInfoMapper;
    @Autowired
    private CurrentContextMapper currentContextMapper;
    @Autowired
    private MingchuangOrderMapper mingchuangOrderMapper;

    @PostMapping("/infoVerify")
    @ApiOperation("OBU信息验证 2070")
    public JSONResult infoVerify(@RequestBody ObuInfoVerifyRequest req) {
        log.info("OBU信息验证:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        //检查是否有重复的ObuId
        QueryWrapper<EtcObu> etcObuQueryWrapper = new QueryWrapper();
        etcObuQueryWrapper.eq("OBUId", req.getObuId());
        List<EtcObu> etcObuList = obuService.queryObjects(etcObuQueryWrapper);
        if (!CollectionUtils.isEmpty(etcObuList)) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("该OBU设备不能重复激活！");
            return result;
        }
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());

        CarInfo carInfo = carInfoService.get(ctx.getCarId());

        req.setClientNo(userProperty.getClientNo());
        req.setVehPlate(carInfo.getVehPlate());
        req.setVehColor(carInfo.getVehColor());
        result = HttpUtil.post(BusinessType.OBU_INFO_VERIFY, req);
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            ctx.setObuId(req.getObuId());
            ctx.setEtcCardNo(req.getCardNo());
            currentContextService.update(ctx);
            //第三方接口请求和返回数据入库
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("businessType", BusinessType.OBU_INFO_VERIFY);
            jsonObject.put("requestData", req);
            jsonObject.put("resultData", result);
            ctx.setJsonData(JSON.toJSONString(jsonObject));
            currentContextService.update(ctx);
        }

        return result;
    }

    @PostMapping("/activeApply")
    @ApiOperation("OBU激活申请 1140")
    public JSONResult activeApply(@RequestBody ObuActiveApplyRequest req) {
        log.info("OBU激活申请:{}", JSON.toJSONString(req));
        req.setClientNo(userProperty.getClientNo());
        req.setOptBy(userProperty.getOptBy());
        return HttpUtil.post(BusinessType.OBU_ACTIVE_APPLY, req);
    }

    @PostMapping("/dataEnc")
    @ApiOperation("OBU数据加密 1009")
    public JSONResult dataEnc(@RequestBody ObuDataEncRequest req) {
        log.info("OBU数据加密:{}", JSON.toJSONString(req));
        req.setClientNo(userProperty.getClientNo());

        //加密数据
        String cmd = null;
        if (req.getType() == 2) {
            cmd = OBUDataEncUtil.dataEnc2(req.getBeginDate(), req.getEndDate());
            req.setCmd(cmd);
        } else if (req.getType() == 1) {
            CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
            CarInfo carInfo = carInfoService.get(ctx.getCarId());
            cmd = OBUDataEncUtil.dataEnc1(carInfo);
            req.setCmd(cmd);
        }
        JSONResult result = HttpUtil.post(BusinessType.OBU_DATA_ENC, req);

        if (result.getCode().equals(JSONResult.SUCCESS)) {
            if (req.getType() == 2 || req.getType() == 1) {
                JSONObject json = JSON.parseObject(result.getRspData());
                String mac = json.getString("mac");
                json.put("data", cmd);
                json.put("mac", mac);
                result.setRspData(json.toJSONString());
            }
        }

        return result;
    }

    @PostMapping("/obuDataEnc")
    @ApiOperation("OBU脱离激活数据加密 1009")
    public JSONResult obuDataEnc(@RequestBody ObuDataEncRequest req) {
        log.info("OBU脱离激活数据加密:{}", JSON.toJSONString(req));
        req.setClientNo(userProperty.getClientNo());

        //加密数据
        JSONResult result = HttpUtil.post(BusinessType.OBU_DATA_ENC, req);

        if (result.getCode().equals(JSONResult.SUCCESS)) {
            JSONObject json = JSON.parseObject(result.getRspData());
            String mac = json.getString("mac");
            json.put("data", req.getCmd());
            json.put("mac", mac);
            result.setRspData(json.toJSONString());
        }

        return result;
    }

    @PostMapping("/submitFallActivateInfo")
    @ApiOperation("提交脱离激活用户信息")
    public JSONResult submitFallActivateInfo(@RequestBody SubmitFallActivateRequest req) {
        JSONResult result = new JSONResult();
        log.info("提交脱离激活用户信息:{}", JSON.toJSONString(req));
        if (null == req) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查");
            return result;
        }
        Date date = new Date();
        EtcFallActivate etcFallActivate = new EtcFallActivate();
        etcFallActivate.setId(Sequence.getId());
        etcFallActivate.setDeleteFlag(0);
        etcFallActivate.setEtcSn(req.getEtcSn());
        etcFallActivate.setImages(req.getImages());
        etcFallActivate.setName(req.getName());
        etcFallActivate.setObuDeviceSn(req.getObuDeviceSn());
        etcFallActivate.setOrderId(req.getOrderId());
        etcFallActivate.setStatus(0);
        etcFallActivate.setChannelType(0);
        etcFallActivate.setVehiclePlate(req.getVehiclePlate());
        etcFallActivate.setUserId(req.getUserId());
        etcFallActivate.setUpdatedTime(date);
        etcFallActivate.setCreateTime(date);
        etcFallActivate.setApplyTime(date);
        int r = etcFallActivateService.save(etcFallActivate);
        if (r > 0) {
            JSONObject json = new JSONObject();
            json.put("etcFallActivateId", etcFallActivate.getId());
            result.setRspData(json.toJSONString());
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("信息提交失败");
        }
        return result;
    }

    @PostMapping("/updateFallActivateStatus")
    @ApiOperation("更新脱离激活状态")
    public JSONResult updateFallActivateStatus(@ApiParam(value = "脱离激活申请信息ID") @RequestParam String etcFallActivateId, @ApiParam(value = "激活结果") @RequestParam Integer status) {
        JSONResult result = new JSONResult();
        log.info("更新脱离激活状态:{}", etcFallActivateId);
        if (null == etcFallActivateId) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查");
            return result;
        }
        EtcFallActivate etcFallActivate = etcFallActivateService.queryObject(etcFallActivateId);
        Date date = new Date();
        etcFallActivate.setStatus(status);
        etcFallActivate.setUpdatedTime(date);
        int r = etcFallActivateService.update(etcFallActivate);
        if (r > 0) {
            JSONObject json = new JSONObject();
            json.put("etcFallActivateId", etcFallActivate.getId());
            result.setRspData(json.toJSONString());
        } else {
            result.setCode(JSONResult.FAIL);
            result.setMessage("更新脱离激活状态失败");
        }
        return result;
    }

    @PostMapping("/activeConfirm")
    @ApiOperation("OBU激活确认 1141")
    public JSONResult activeConfirm(@RequestBody ObuActiveConfirmParam req) {
        log.info("OBU激活确认:{}", JSON.toJSONString(req));
        JSONResult result = null;
        ObuActiveConfirmRequest request = new ObuActiveConfirmRequest();
        request.setTradeNo(req.getTradeNo());
        result = HttpUtil.post(BusinessType.OBU_ACTIVE_CONFIRM, request);
        if (result.getMessage().indexOf("请勿重复上传") > 0) {
            result.setCode(JSONResult.SUCCESS);
            //第三方接口请求和返回数据入库
            CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
            if (ctx != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("businessType", BusinessType.OBU_ACTIVE_CONFIRM);
                jsonObject.put("requestData", req);
                jsonObject.put("resultData", result);
                ctx.setJsonData(JSON.toJSONString(jsonObject));
                currentContextService.update(ctx);
                return result;
            }
        }
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            //第三方接口请求和返回数据入库
            CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
            if (ctx != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("businessType", BusinessType.OBU_ACTIVE_CONFIRM);
                jsonObject.put("requestData", req);
                jsonObject.put("resultData", result);
                ctx.setJsonData(JSON.toJSONString(jsonObject));
                currentContextService.update(ctx);
            }
        }
        return result;
    }

    @PostMapping("/activeVerify")
    @ApiOperation("OBU激活验证 2140")
    public JSONResult activeVerify(@RequestBody ObuActiveVerifyRequest req) {
        log.info("OBU激活验证:{}", JSON.toJSONString(req));
        JSONResult result = null;
        req.setClientNo(userProperty.getClientNo());
        result = HttpUtil.post(BusinessType.OUB_ACTIV_VERIFY, req);
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            //第三方接口请求和返回数据入库
            QueryWrapper<CurrentContext> wrapper = new QueryWrapper<>();
            wrapper.eq("obuId", req.getObuId());
            wrapper.eq("pay_mode", 1);
            List<CurrentContext> currentContextList = currentContextService.queryObjects(wrapper);
            if (!CollectionUtils.isEmpty(currentContextList)) {
                CurrentContext ctx = currentContextList.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("businessType", BusinessType.OUB_ACTIV_VERIFY);
                jsonObject.put("requestData", req);
                jsonObject.put("resultData", result);
                ctx.setJsonData(JSON.toJSONString(jsonObject));
                currentContextService.update(ctx);
            }
        }
        return result;
    }

    @PostMapping("/activeComplete")
    @ApiOperation("OBU激活完成 2141")
    public JSONResult activComplete(@RequestBody ObuActiveCompleteRequest req) {
        JSONResult result = new JSONResult();
        log.info("OBU激活完成:{}", JSON.toJSONString(req));
        //检查是否有重复的ObuId
        QueryWrapper<EtcObu> etcObuQueryWrapper = new QueryWrapper();
        etcObuQueryWrapper.eq("OBUId", req.getObuId());
        List<EtcObu> etcObuList = obuService.queryObjects(etcObuQueryWrapper);
        if (!CollectionUtils.isEmpty(etcObuList)) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("该OBU设备不能重复激活！！！");
            return result;
        }
        String obuId = req.getObuId();
        req.setClientNo(userProperty.getClientNo());
        req.setOptBy(userProperty.getOptBy());
        result = HttpUtil.post(BusinessType.OUB_ACTIV_COMPLETE, req);
        if (JSONResult.SUCCESS.equals(result.getCode())) {
            String userId = req.getUserId();
            obuService.activeComplete(obuId, userId);
            //第三方接口请求和返回数据入库
            QueryWrapper<CurrentContext> wrapper = new QueryWrapper<>();
            wrapper.eq("obuId", req.getObuId());
            wrapper.eq("pay_mode", 1);
            List<CurrentContext> currentContextList = currentContextService.queryObjects(wrapper);
            if (!CollectionUtils.isEmpty(currentContextList)) {
                CurrentContext ctx = currentContextList.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("businessType", BusinessType.OUB_ACTIV_COMPLETE);
                jsonObject.put("requestData", req);
                jsonObject.put("resultData", result);
                ctx.setJsonData(JSON.toJSONString(jsonObject));
                currentContextService.update(ctx);
            }
        }
        return result;
    }

    @PostMapping("/cmgActiveCompleteH")
    @ApiOperation("激活后第三方数据回传（好司机特殊处理）")
    public JSONResult cmgActiveCompleteH(@RequestParam String userId) {
        JSONResult result = new JSONResult();
        QueryWrapper<CurrentContext> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        CurrentContext ctx = currentContextMapper.selectOne(qw);

        ApplyInfo applyInfo = applyInfoMapper.selectById(ctx.getApplyId());

        QueryWrapper<EtcOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", ctx.getOrderNo());
        EtcOrder etcOrder = mingchuangOrderMapper.selectOne(wrapper);

        //推送激活数据给到好司机
        try{
            SysConfig cyCustomConfig = sysConfigService.queryByKey("cy_custom_config");
            String thirdCustom = cyCustomConfig.getConfigValue();
            JSONObject object = JSON.parseObject(thirdCustom);
            //同步消息给好司机
            JSONObject obj = new JSONObject();
            obj.put("vehiclePlate", etcOrder.getVehPlate());
            obj.put("phone", DesensitizedUtil.desensitized(etcOrder.getPhone(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
            Map<String, String> m = new HashMap<>();
            m.put("remark", obj.toJSONString());
            m.put("request", object.getString("request"));
            m.put("request_type", object.getString("request_type"));
            m.put("platform", object.getString("platform"));
            m.put("cdk", etcOrder.getPayNo());
            m.put("equipment_code", etcOrder.getBody());
            m.put("obu_code",ctx.getObuId());
            m.put("class", object.getString("class"));
            m.put("method", object.getString("method"));
            String s = PayUtil.generateSign(m, object.getString("secreKey"));
            m.put("sign", s.substring(8, 24).toUpperCase());
            String r = HttpUtils.doPost(object.getString("url"), m);
            if (!StringUtils.isEmpty(r)) {
                JSONObject jsonObject = JSON.parseObject(r);
                result.setRspData(r);
                log.info(jsonObject.toJSONString());
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("同步消息给好司机系统出现异常:{}", JSON.toJSONString(etcOrder));
        }
        return result;
    }
}
